﻿/* Copyright (C) 2007-2010 STS Soft

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using STSdb.General.Buffers;

namespace STSdb.General.Streams
{
    public static class StreamExtensions
    {
        public const int BUFFER_SIZE = 64 * 1024;

        public static int CompareTo(this Stream self, Stream other)
        {
            byte[] buffer1 = new byte[BUFFER_SIZE];
            byte[] buffer2 = new byte[BUFFER_SIZE];

            self.Seek(0, SeekOrigin.Begin);
            other.Seek(0, SeekOrigin.Begin);

            while (true)
            {
                int count1 = self.Read(buffer1, 0, BUFFER_SIZE);
                int count2 = other.Read(buffer2, 0, BUFFER_SIZE);

                int chunk = Math.Min(count1, count2);
                if (chunk == 0)
                    break;

                int cmp = buffer1.CompareTo(buffer2, chunk);
                if (cmp != 0)
                    return cmp;

                if (chunk < BUFFER_SIZE)
                    break;
            }

            return self.Length.CompareTo(other.Length);
        }

        public static bool EqualsTo(this Stream self, Stream other)
        {
            if (self.Length != other.Length)
                return false;

            return CompareTo(self, other) == 0;
        }
    }
}
